package com.example.teacherservice.controller;

import com.example.teacherservice.dto.ClassInfo;
import com.example.teacherservice.dto.StudentBasicDTO;
import com.example.teacherservice.dto.StudentDTO;
import com.example.teacherservice.dto.StudentDetailDTO;
import com.example.teacherservice.entity.Student;
import com.example.teacherservice.repository.StuClassRepository;
import com.example.teacherservice.service.ClassService;
import com.example.teacherservice.service.CourseService;
import com.example.teacherservice.service.StudentService;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.teacherservice.entity.StuCourseAppraise;
import com.example.teacherservice.entity.StuCouProgress;
import com.example.teacherservice.repository.StuCourseAppraiseRepository;
import com.example.teacherservice.entity.StuCouColletion;
import com.example.teacherservice.repository.StuCourseCollectionRepository;
import com.example.teacherservice.repository.StuCourseProgressRepository;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/spoc/api/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private StuClassRepository stuClassRepository;

    @Autowired
    private StuCourseAppraiseRepository stuCourseAppraiseRepository;

    @Autowired
    private StuCourseCollectionRepository stuCourseCollectionRepository;

    @Autowired
    private StuCourseProgressRepository stuCourseProgressRepository;

    @Autowired
    private ClassService classService;

    @GetMapping
    public ResponseEntity<?> getStudents() {
        try {
            List<StudentDTO> students = studentService.getAllStudents()
                    .stream()
                    .map(student -> {
                        String username = null;
                        try {
                            username = student.getUser() != null ?
                                    student.getUser().getUsername() : null;
                        } catch (EntityNotFoundException e) {
                            System.out.printf("学生 {} 关联了无效用户ID: {}",
                                    student.getId(), student.getUserId());
                        }
                        return new StudentDTO(
                                student.getId(),
                                student.getName(),
                                username
                        );
                    })
                    .collect(Collectors.toList());

            return ResponseEntity.ok(students);
        } catch (Exception e) {
            System.out.printf("获取学生列表失败", e);
            return ResponseEntity.internalServerError()
                    .body(Map.of(
                            "status", 500,
                            "message", "获取学生列表失败",
                            "timestamp", System.currentTimeMillis()
                    ));
        }
    }

    @GetMapping("/search")
    public List<Student> searchStudents(@RequestParam String keyword) {
        return studentService.searchStudents(keyword);
    }

    @PostMapping("/batch-add-to-class")
    public ResponseEntity<Map<String, Object>> batchAddStudentsToClass(
            @RequestParam Long classId,
            @RequestBody List<Long> studentIds) {

        Map<String, Object> response = new HashMap<>();

        try {
            int addedCount = studentService.batchAddStudentsToClass(classId, studentIds);

            response.put("success", true);
            response.put("addedCount", addedCount);
            response.put("totalCount", studentIds.size());
            response.put("message", "成功添加 " + addedCount + " 名学生到班级");

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量添加学生失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    // 单个学生添加到班级
    @PostMapping("/{classId}/students/{studentId}")
    public ResponseEntity<Map<String, Object>> addStudentToClass(
            @PathVariable Long classId,
            @PathVariable Long studentId) {

        Map<String, Object> response = new HashMap<>();
        try {
            int result = studentService.batchAddStudentsToClass(classId, List.of(studentId));
            response.put("success", true);
            response.put("message", "成功添加学生到班级");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 从班级移除单个学生
    @DeleteMapping("/{classId}/students/{studentId}")
    public ResponseEntity<Map<String, Object>> removeStudentFromClass(
            @PathVariable Long classId,
            @PathVariable Long studentId) {

        Map<String, Object> response = new HashMap<>();
        try {
            int result = studentService.removeStudentFromClass(classId, studentId);
            if (result > 0) {
                response.put("success", true);
                response.put("message", "成功从班级移除学生");
            } else {
                response.put("success", false);
                response.put("message", "学生不在该班级中");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 批量从班级移除学生
    @DeleteMapping("/{classId}/students/batch")
    public ResponseEntity<Map<String, Object>> batchRemoveStudentsFromClass(
            @PathVariable Long classId,
            @RequestBody List<Long> studentIds) {

        Map<String, Object> response = new HashMap<>();
        try {
            int removedCount = studentService.batchRemoveStudentsFromClass(classId, studentIds);
            response.put("success", true);
            response.put("removedCount", removedCount);
            response.put("message", "成功从班级移除 " + removedCount + " 名学生");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 新增端点：根据userId获取学生信息
    // 在StudentController中添加
    @GetMapping("/by-user-id/{userId}")
    public ResponseEntity<?> getStudentIdByUserId(@PathVariable Long userId) {
        try {
            Long studentId = studentService.findStudentIdByUserId(userId);
            if (studentId == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of(
                                "success", false,
                                "message", "未找到该用户对应的学生信息"
                        ));
            }
            return ResponseEntity.ok(Map.of("studentId", studentId));
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 新增端点：获取学生详细信息（包含用户信息）
    @GetMapping("/detail/by-user/{userId}")
    public ResponseEntity<?> getStudentDetailByUserId(@PathVariable Long userId) {
        try {
            Student student = studentService.getStudentDetailByUserId(userId);
            List<ClassInfo> classes = stuClassRepository.findClassesByStudentId(student.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("id", student.getId());
            response.put("userId", student.getUserId());
            response.put("stuName", student.getStuName());
            response.put("stuStudyTime", student.getStuStudyTime());
            response.put("stuScore", student.getStuScore());

            // 修改这里：使用getUsername()而不是getName()
            if(student.getUser() != null) {
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", student.getUser().getId());
                userInfo.put("username", student.getUser().getUsername());
                userInfo.put("role", student.getUser().getRole());
                response.put("user", userInfo);
            } else {
                response.put("user", null);
            }

            response.put("classes", classes);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    // 在StudentController中添加
    @GetMapping("/dto/by-user/{userId}")
    public ResponseEntity<?> getStudentDTOByUserId(@PathVariable Long userId) {
        try {
            Student student = studentService.getStudentDetailByUserId(userId);
            StudentDetailDTO dto = new StudentDetailDTO(student);
            return ResponseEntity.ok(dto);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取所有学生基本信息（不分页）
     * @return 所有学生列表
     */
    @GetMapping("/all")
    public ResponseEntity<?> getAllStudentsBasicInfo() {
        try {
            List<Student> students = studentService.getAllStudent();

            // 转换为基本DTO，不包含用户信息
            List<StudentBasicDTO> dtos = students.stream()
                    .map(student -> new StudentBasicDTO(
                            student.getId(),
                            student.getStuName(),
                            student.getStuStudyTime(),
                            student.getStuScore(),
                            student.getClock(),
                            student.getCreateTime()
                    ))
                    .collect(Collectors.toList());

            return ResponseEntity.ok(dtos);

        } catch (Exception e) {
            System.out.printf("获取学生列表失败", e);
            return ResponseEntity.internalServerError()
                    .body(Map.of(
                            "status", 500,
                            "message", "获取学生列表失败",
                            "timestamp", System.currentTimeMillis()
                    ));
        }
    }

    @GetMapping("/{studentId}/detail")
    public ResponseEntity<?> getStudentDetailById(@PathVariable Long studentId) {
        try {
            Student student = studentService.getStudentDetailById(studentId);
            List<ClassInfo> classes = stuClassRepository.findClassesByStudentId(studentId);

            // 获取课程相关数据
            List<StuCouProgress> courseProgresses = stuCourseProgressRepository.findByStuId(studentId);
            List<StuCouColletion> courseCollections = stuCourseCollectionRepository.findByStuId(studentId);
            List<StuCourseAppraise> courseAppraises = stuCourseAppraiseRepository.findByStudentId(studentId);

            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("id", student.getId());
            response.put("stuName", student.getStuName());
            response.put("stuStudyTime", student.getStuStudyTime());
            response.put("stuScore", student.getStuScore());
            response.put("clock", student.getClock());
            response.put("createTime", student.getCreateTime());
            response.put("classes", classes);

            // 课程相关数据
            response.put("courseProgresses", courseProgresses.stream()
                    .map(this::convertToProgressDTO)
                    .collect(Collectors.toList()));

            response.put("courseCollections", courseCollections.stream()
                    .map(this::convertToCollectionDTO)
                    .collect(Collectors.toList()));

            response.put("courseAppraises", courseAppraises.stream()
                    .map(this::convertToAppraiseDTO)
                    .collect(Collectors.toList()));

            return ResponseEntity.ok(response);

        } catch (EntityNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of(
                            "status", 404,
                            "message", "未找到该学生信息",
                            "timestamp", System.currentTimeMillis()
                    ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body(Map.of(
                            "status", 500,
                            "message", "获取学生详情失败",
                            "timestamp", System.currentTimeMillis()
                    ));
        }
    }

    private Map<String, Object> convertToProgressDTO(StuCouProgress progress) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", progress.getId());
        dto.put("courseId", progress.getCouId());
        dto.put("chapterId", progress.getChaId());
        dto.put("learnedDuration", progress.getLearnedDuration());
        dto.put("mediaProgress", progress.getMediaProgress());
        dto.put("mediaDuration", progress.getMediaDuration());
        dto.put("learnedStatus", progress.getLearnedStatus());
        dto.put("positioning", progress.getPositioning());
        dto.put("createTime", progress.getCreateTime());
        dto.put("updateTime", progress.getUpdateTime());
        return dto;
    }

    private Map<String, Object> convertToCollectionDTO(StuCouColletion collection) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", collection.getId());
        dto.put("courseId", collection.getCouId());
        dto.put("createTime", collection.getCreateTime());
        dto.put("updateTime", collection.getUpdateTime());
        return dto;
    }

    private Map<String, Object> convertToAppraiseDTO(StuCourseAppraise appraise) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", appraise.getId());
        dto.put("courseId", appraise.getCourseId());
        dto.put("content", appraise.getContent());
        dto.put("score", appraise.getScore());
        dto.put("createTime", appraise.getCreateTime());
        return dto;
    }

    @GetMapping("/course-names")
    public ResponseEntity<?> getCourseNamesByIds(@RequestParam String courseIds) {
        try {
            // 将逗号分隔的字符串转换为Long列表
            List<Long> ids = Arrays.stream(courseIds.split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toList());

            Map<Long, String> courseNames = studentService.getCourseNamesByIds(ids);
            return ResponseEntity.ok(courseNames);
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body(Map.of(
                            "status", 500,
                            "message", "获取课程名称失败",
                            "timestamp", System.currentTimeMillis()
                    ));
        }
    }
}